package com.smarttest.common.util.mqtt;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.msgpack.MessagePack;

import com.smarttest.common.util.mqtt.v1.Gpsmsg;
import com.smarttest.common.util.mqtt.v1.GpsmsgList;

public class MQTT_DSDZ_V1 {
//	private static int sleeptime = 10000;
//	private static int code = 3130;//只能为3164
//	private static String simno = "F08060B1D30";
	/**
	 * 发送DSDZ_v1报文
	 * @param url
	 * @param topic
	 * @param imei
	 * @param internal
	 * @return
	 * @throws IOException
	 */
    public static Map<Integer, Date> sendmsg(String url,String topic,String imei,int internal) throws IOException {
//
//        String topic = "httx/input/gpsmsg/3164";
        int qos = 1;
////        String broker = "tcp://172.30.4.2:1883";
////                String broker = "tcp://60.28.195.206:883";
//        //        String broker = "tcp://123.56.0.101:1883";
////         String broker = "tcp://172.17.100.31:1883";   //天津线上     
////                 String broker = "tcp://172.16.18.10:1883";//aliyun  内网
//                  String broker  = "tcp://118.178.33.52:883";//aliyun  外网
////		private static String broker = "tcp://60.28.195.206:883";//线上

        Map<Integer,Date> m = new HashMap<Integer, Date>();
		int code = Integer.parseInt(imei.substring(0, 4));
		String deviceno = imei.substring(4, imei.length());
		int index = 1;
        MemoryPersistence persistence = new MemoryPersistence();
        try {
            MqttAsyncClient sampleClient = new MqttAsyncClient(url, MqttAsyncClient.generateClientId(), persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(false);
            System.out.println("Connecting to broker: " + url);
            sampleClient.connect(connOpts);
            long t1 = System.currentTimeMillis();
            long pubSum = 0;
//            System.out.println("Connected,t1:" + t1);
			int count=1;
            @SuppressWarnings("resource")
//			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(CommonUtils.getFilePath("/TestData/"+BaseTask.getTestEnv()+"/mqtt_dsdz_v1.txt"))));
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\workspace\\DSP_MessageStorage\\TestData\\product\\mqtt_dsdz_v1.txt")));
            for (String line = br.readLine(); line != null; line = br.readLine()) {
				String[] aa=line.split("/");
				System.out.println("便携定式冷链--：");
				System.out.print("第"+count+"条MQTT_dsdz: ");
            	Date currentTime = new Date();
            	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
				String dateStringtime = formatter.format(currentTime);
                Gpsmsg loc = new Gpsmsg();
                loc.setCmd("gpsmsg");
                loc.setCode(code);
                loc.setMode(2);
                loc.setDeviceno(deviceno);
                loc.setTime(dateStringtime);
                loc.setLat(Double.parseDouble(aa[0]));
                loc.setLng(Double.parseDouble(aa[1]));
                loc.getGpsStatus().setGps(1);
                loc.getGpsStatus().setAcc(0);
                loc.setSpeed(0);
                loc.getGpsStatus().setBp(Integer.parseInt(aa[3]));
                loc.getTemperature().setT1(Double.parseDouble(aa[4]));
                loc.getTemperature().setHumi(Double.parseDouble(aa[5]));
                System.out.println(loc);               
                List<Gpsmsg> gpsmsgList = new ArrayList<Gpsmsg>();
                gpsmsgList.add(loc);
                GpsmsgList gl = new GpsmsgList();
                gl.setGpsmsgList(gpsmsgList);
                
                MessagePack msgpack = new MessagePack();
                byte[] raw = null;
                raw = ZipUtils.gzip(msgpack.write(gl));
                MqttMessage message = new MqttMessage(raw);
                message.setQos(qos);
                long t2 = System.currentTimeMillis();
                sampleClient.publish(topic, message);
                m.put(index, currentTime);
                index++;
                pubSum += System.currentTimeMillis() - t2;
                count++;
                if (count == 121) {
                	try {
                        Thread.sleep(210*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                else {
                	try {
                        Thread.sleep(internal*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            long sum = System.currentTimeMillis() - t1;

            System.out.println("Message published,pubSum:" + pubSum + ",total sum:" + sum);
            sampleClient.disconnect();
            System.out.println("Disconnected");
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
        return m;
    }
}
